import json
import re


def fix_json_file(filename):
    # 读取文件内容
    with open(filename, 'rb') as f:
        content_bytes = f.read()

    # 检测并移除BOM
    if content_bytes.startswith(b'\xef\xbb\xbf'):
        content = content_bytes[3:].decode('utf-8')
        print("检测到并移除了UTF-8 BOM")
    else:
        content = content_bytes.decode('utf-8')

    # 修复中文逗号问题
    content = content.replace('，', ',')

    # 修复其他可能的语法错误
    # 例如确保所有键和字符串值都用双引号包围
    content = re.sub(r'(\w+):', r'"\1":', content)

    # 写入修复后的文件
    fixed_filename = filename.replace('.json', '_fixed.json')
    with open(fixed_filename, 'w', encoding='utf-8') as f:
        f.write(content)

    # 尝试解析修复后的JSON
    try:
        with open(fixed_filename, 'r', encoding='utf-8') as f:
            data = json.load(f)
        print(f"JSON文件修复成功！已保存为: {fixed_filename}")
        return data
    except json.JSONDecodeError as e:
        print(f"修复后仍然存在JSON语法错误: {e}")
        return None


# 使用函数修复文件
data = fix_json_file('three-domain_java_kg.json')
if data:
    print(f"节点数量: {len(data.get('nodes', []))}")
    print(f"边数量: {len(data.get('edges', []))}")